# Windows IIS配置脚本
# 配置IIS作为反向代理服务器

param(
    [Parameter(Mandatory=$true)]
    [string]$Domain
)

Write-Host "🔧 配置IIS for $Domain" -ForegroundColor Green
Write-Host "=======================" -ForegroundColor Green

# 检查管理员权限
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Host "❌ 请以管理员身份运行PowerShell" -ForegroundColor Red
    exit 1
}

$projectDir = "C:\inetpub\whatsapp-platform"

try {
    # 导入IIS模块
    Import-Module WebAdministration

    # 删除默认网站（如果存在）
    if (Get-Website -Name "Default Web Site" -ErrorAction SilentlyContinue) {
        Remove-Website -Name "Default Web Site"
        Write-Host "✅ 已删除默认网站" -ForegroundColor Green
    }

    # 创建应用程序池
    $appPoolName = "WhatsAppPlatformPool"
    if (Get-IISAppPool -Name $appPoolName -ErrorAction SilentlyContinue) {
        Remove-WebAppPool -Name $appPoolName
    }
    
    New-WebAppPool -Name $appPoolName
    Set-ItemProperty -Path "IIS:\AppPools\$appPoolName" -Name processModel.identityType -Value ApplicationPoolIdentity
    Set-ItemProperty -Path "IIS:\AppPools\$appPoolName" -Name recycling.periodicRestart.time -Value "00:00:00"
    Set-ItemProperty -Path "IIS:\AppPools\$appPoolName" -Name processModel.idleTimeout -Value "00:00:00"
    
    Write-Host "✅ 应用程序池创建完成" -ForegroundColor Green

    # 创建网站
    $siteName = "WhatsAppPlatform"
    if (Get-Website -Name $siteName -ErrorAction SilentlyContinue) {
        Remove-Website -Name $siteName
    }
    
    New-Website -Name $siteName -Port 80 -HostHeader $Domain -PhysicalPath "$projectDir\frontend\build" -ApplicationPool $appPoolName
    
    Write-Host "✅ IIS网站创建完成" -ForegroundColor Green

    # 创建web.config文件用于反向代理
    $webConfig = @"
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <!-- API反向代理规则 -->
                <rule name="ReverseProxyInboundAPI" stopProcessing="true">
                    <match url="^api/(.*)" />
                    <action type="Rewrite" url="http://127.0.0.1:3001/api/{R:1}" />
                </rule>
                
                <!-- Socket.IO反向代理规则 -->
                <rule name="ReverseProxyInboundSocketIO" stopProcessing="true">
                    <match url="^socket\.io/(.*)" />
                    <action type="Rewrite" url="http://127.0.0.1:3001/socket.io/{R:1}" />
                </rule>
                
                <!-- 上传文件代理规则 -->
                <rule name="ReverseProxyInboundUploads" stopProcessing="true">
                    <match url="^uploads/(.*)" />
                    <action type="Rewrite" url="http://127.0.0.1:3001/uploads/{R:1}" />
                </rule>
                
                <!-- SPA路由规则 - 必须放在最后 -->
                <rule name="SPARouting" stopProcessing="true">
                    <match url=".*" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                        <add input="{REQUEST_URI}" pattern="^/(api|socket\.io|uploads)" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="/index.html" />
                </rule>
            </rules>
        </rewrite>
        
        <!-- 安全头设置 -->
        <httpProtocol>
            <customHeaders>
                <add name="X-Frame-Options" value="SAMEORIGIN" />
                <add name="X-XSS-Protection" value="1; mode=block" />
                <add name="X-Content-Type-Options" value="nosniff" />
                <add name="Referrer-Policy" value="no-referrer-when-downgrade" />
            </customHeaders>
        </httpProtocol>
        
        <!-- 压缩设置 -->
        <urlCompression doStaticCompression="true" doDynamicCompression="true" />
        <httpCompression>
            <dynamicTypes>
                <add mimeType="application/json" enabled="true" />
                <add mimeType="application/javascript" enabled="true" />
                <add mimeType="text/css" enabled="true" />
                <add mimeType="text/html" enabled="true" />
            </dynamicTypes>
        </httpCompression>
        
        <!-- 静态文件缓存 -->
        <staticContent>
            <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="31536000" />
            <remove fileExtension=".js" />
            <mimeMap fileExtension=".js" mimeType="application/javascript" />
        </staticContent>
        
        <!-- 上传文件大小限制 -->
        <security>
            <requestFiltering>
                <requestLimits maxAllowedContentLength="10485760" />
            </requestFiltering>
        </security>
        
        <!-- 默认文档 -->
        <defaultDocument>
            <files>
                <add value="index.html" />
            </files>
        </defaultDocument>
    </system.webServer>
</configuration>
"@

    # 写入web.config文件
    Set-Content -Path "$projectDir\frontend\build\web.config" -Value $webConfig -Encoding UTF8
    Write-Host "✅ web.config配置文件创建完成" -ForegroundColor Green

    # 设置文件权限
    $acl = Get-Acl "$projectDir"
    $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("IIS_IUSRS", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
    $acl.SetAccessRule($accessRule)
    $acl | Set-Acl "$projectDir"
    
    Write-Host "✅ 文件权限设置完成" -ForegroundColor Green

    # 启动网站和应用程序池
    Start-WebAppPool -Name $appPoolName
    Start-Website -Name $siteName
    
    Write-Host "✅ 网站启动完成" -ForegroundColor Green

    # 配置防火墙规则
    Write-Host "`n🔒 配置Windows防火墙..." -ForegroundColor Yellow
    
    try {
        # 允许HTTP流量
        New-NetFirewallRule -DisplayName "WhatsApp Platform HTTP" -Direction Inbound -Protocol TCP -LocalPort 80 -Action Allow -ErrorAction SilentlyContinue
        New-NetFirewallRule -DisplayName "WhatsApp Platform HTTPS" -Direction Inbound -Protocol TCP -LocalPort 443 -Action Allow -ErrorAction SilentlyContinue
        New-NetFirewallRule -DisplayName "WhatsApp Platform Backend" -Direction Inbound -Protocol TCP -LocalPort 3001 -Action Allow -ErrorAction SilentlyContinue
        
        Write-Host "✅ 防火墙规则配置完成" -ForegroundColor Green
    } catch {
        Write-Host "⚠️  防火墙配置可能需要手动设置" -ForegroundColor Yellow
    }

    Write-Host "`n🎉 IIS配置完成！" -ForegroundColor Green
    Write-Host "==================" -ForegroundColor Green
    
    Write-Host "`n📋 配置信息:" -ForegroundColor Cyan
    Write-Host "   网站名称: $siteName" -ForegroundColor White
    Write-Host "   应用程序池: $appPoolName" -ForegroundColor White
    Write-Host "   域名: $Domain" -ForegroundColor White
    Write-Host "   物理路径: $projectDir\frontend\build" -ForegroundColor White
    
    Write-Host "`n🔗 访问地址:" -ForegroundColor Cyan
    Write-Host "   HTTP: http://$Domain" -ForegroundColor White
    Write-Host "   API健康检查: http://$Domain/api/health" -ForegroundColor White
    
    Write-Host "`n📝 下一步操作:" -ForegroundColor Yellow
    Write-Host "1. 测试网站访问:" -ForegroundColor White
    Write-Host "   在浏览器中访问 http://$Domain" -ForegroundColor Gray
    
    Write-Host "`n2. 配置SSL证书（推荐）:" -ForegroundColor White
    Write-Host "   - 在IIS管理器中绑定SSL证书" -ForegroundColor Gray
    Write-Host "   - 或使用Let's Encrypt for IIS" -ForegroundColor Gray
    
    Write-Host "`n3. 监控应用状态:" -ForegroundColor White
    Write-Host "   pm2 status" -ForegroundColor Gray
    Write-Host "   pm2 logs whatsapp-platform" -ForegroundColor Gray
    
    Write-Host "`n🔧 管理命令:" -ForegroundColor Yellow
    Write-Host "   重启应用: pm2 restart whatsapp-platform" -ForegroundColor Gray
    Write-Host "   重启网站: Restart-Website -Name '$siteName'" -ForegroundColor Gray
    Write-Host "   重启应用池: Restart-WebAppPool -Name '$appPoolName'" -ForegroundColor Gray

} catch {
    Write-Host "`n❌ IIS配置过程中出现错误: $($_.Exception.Message)" -ForegroundColor Red
    Write-Host "详细错误信息: $($_.Exception)" -ForegroundColor Red
    exit 1
} 